<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Aadmins extends Controller_Abase_Adefaultactions {

    public function before() {
        parent::before();
        if (Cookie::get('role', null) != 0) die('Access denied!');
    }

    public function action_add() {
        $newObj = ORM::factory($this->request->controller());
        $fields = arr::path($this->params(), 'fields'); // Получаем поля сверху

        foreach ($fields as $key => $item) { // Заполняем значения полей
        	$pass = $this->request->post('pass');

            if ($fields[$key]['type'] == 'password' && !empty($pass)) {
                $newObj->$key = md5($this->request->post($key));
            } elseif ($fields[$key]['type'] != 'password') {
                $newObj->$key = $this->request->post($key);
            }
        }

        $newObj->save();
        $this->redirect('administration/'.$this->request->controller().'/'.$this->request->param('page'));
    }

    public function action_edit() {
        $obj = ORM::factory($this->request->controller(), $this->request->param('id'));

        if ($this->request->param('save')) {
            $fields = arr::path($this->params(), 'fields'); // Получаем поля сверху

            foreach ($fields as $key => $item) { // Заполняем новые значения полей	
            	$pass = $this->request->post('pass');

	            if ($fields[$key]['type'] == 'password' && !empty($pass)) {
	                $obj->$key = md5($this->request->post($key));
	            } elseif ($fields[$key]['type'] != 'password') {
	                $obj->$key = $this->request->post($key);
	            }
            }

            $obj->save();
            $this->redirect('administration/'.$this->request->controller().'/'.$this->request->param('page').'/edit/'.$this->request->param('id'));
            exit();
        }

        $params = $this->params($obj);
        $this->showDefaultForm($params, $obj, 'edit');
        $this->showPagination(); // Пагинация
        $this->showDefaultList(); // Рендерим список данных и форму редактирования\добавления
    }
}